package com.peng.mybatis.builder.xml;

import cn.hutool.core.lang.Assert;
import com.peng.mybatis.builder.BaseBuilder;
import com.peng.mybatis.io.Resources;
import com.peng.mybatis.session.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder extends BaseBuilder {

    private Element element;

    private String resource;

    private String currentNamespace;

    public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource) throws DocumentException {
        this(new SAXReader().read(inputStream), configuration, resource);
    }

    private XMLMapperBuilder(Document document, Configuration configuration, String resource) {
        super(configuration);
        this.element = document.getRootElement();
        this.resource = resource;
    }

    public void parse() throws Exception {
        if (!configuration.isResourceLoaded(resource)) {
            configurationElement(element);
            configuration.addLoadedResource(resource);
            configuration.addMapper(Resources.classForName(currentNamespace));
        }
    }

    private void configurationElement(Element element) {
        currentNamespace = element.attributeValue("namespace");         
        Assert.notBlank(currentNamespace, "mapper命名空间不能为空");
        buildStatementFromContext(element.elements("select"));
    }

    private void buildStatementFromContext(List<Element> selects) {
        for (Element select : selects) {
            XmlStatementBuilder xmlStatementBuilder = new XmlStatementBuilder(configuration, select, currentNamespace);
            xmlStatementBuilder.parseStatementNode();
        }
    }

}
